
using System;
namespace ttbase
{
    class TTArray<type> : ICloneable
    {
        int _length;
        type[] array;

        public TTArray(int maxlength)
        {
            array = new type[maxlength];
        }
        public int Length
        {
            get
            {
                return _length;
            }
            set
            {
                if (value >= array.Length || value < 0)
                    throw new Exception("out of range.");
                _length = value;
            }
        }
        public int MaxLength
        {
            get
            {
                return array.Length;
            }
        }
        public type this[int index]
        {
            get
            {
                if (index >= _length || index < 0)
                    throw new Exception("out of range.");
                return array[index];
            }
            set
            {
                if (index >= _length || index < 0)
                    throw new Exception("out of range.");
                array[index] = value;
            }
        }
        public void Clear()
        {
            _length = 0;
        }
        public void Append(TTArray<type> arr)
        {
            int newlength = Math.Min(this._length + arr.Length, this.MaxLength);
            for (var i = _length; i < newlength; i++)
            {
                this.array[i] = arr[i - _length];
            }
            this._length = newlength;

        }
        public override string ToString()
        {
            unsafe
            {
                if (typeof(type) == typeof(UInt16))
                {
                    fixed (void* p = (UInt16[])(object)array)
                    {
                        return new string((char*)p, 0, this._length);
                    }
                }
                else if (typeof(type) == typeof(char))
                {

                    fixed (char* p = (char[])(object)array)
                    {
                        return new string(p, 0, this._length);
                    }
                }
                else
                {
                    return "TTArray<" + typeof(type).Name + ">[" + _length + ",max=" + array.Length + "]";
                }
            }
        }
        public object Clone()
        {
            var arr = new TTArray<type>(MaxLength);
            arr.Length = this._length;
            for (var i = 0; i < _length; i++)
            {
                arr[i] = this.array[i];
            }
            return arr;
        }
    }
}

